package com.wo.cloud.auth.controller;

import cn.hutool.core.util.ObjectUtil;
import com.wo.cloud.core.entity.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/4/26 10:34
 * Description: 自定义Oauth2自定义返回格式
 */

@RestController
@RequestMapping("/oauth")
public class OauthController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @PostMapping("/token")
    public Response<?> postAccessToken(Principal principal, @RequestParam
            Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        OAuth2AccessToken oAuth2AccessToken;

        return custom(tokenEndpoint.postAccessToken(principal, parameters).getBody(), parameters);
    }

    /**
     * 自定登录返回格式
     *
     * @param oAuth2AccessToken
     * @return
     */
    private Response<?> custom(OAuth2AccessToken oAuth2AccessToken, Map<String, String> parameters) {
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) oAuth2AccessToken;
        Map<String, Object> data = new LinkedHashMap<>(token.getAdditionalInformation());
        data.put(OAuth2AccessToken.ACCESS_TOKEN, token.getValue());
        data.put(OAuth2AccessToken.BEARER_TYPE, token.getTokenType());
        data.put(OAuth2AccessToken.EXPIRES_IN, token.getExpiresIn());
        data.put(OAuth2AccessToken.TOKEN_TYPE, token.getTokenType());
        data.put(OAuth2AccessToken.SCOPE, token.getScope());
        if (ObjectUtil.isNotNull(token.getRefreshToken())) {
            data.put(OAuth2AccessToken.REFRESH_TOKEN, token.getRefreshToken());
        }

        // 获取client Id
        String clientId = parameters.get("client_id");
        String grantType = parameters.get("grant_type");
        data.put("client_id", clientId);
        data.put("grant_type", grantType);
        return Response.data(data);
    }
}
